package com.cly.cart.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cly.cart.service.CartService;
import com.cly.common.entity.cart.dto.CartDTO;
import com.cly.common.entity.cart.po.Cart;
import com.cly.common.entity.result.Result;
import com.cly.common.exception.CommonException;
import com.cly.common.util.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("cart")
@Slf4j
public class CartController {
    @Autowired
    private CartService cartService;

    /**
     * 添加购物车
     * @param cartDTO
     * @return
     */
    @PostMapping("add")
    public Result addCart(@RequestBody CartDTO cartDTO){
        return cartService.addCart(cartDTO);
    }

    /**
     * 获取购物车
     * @return
     */
    @GetMapping("get")
    public Result getCart(@RequestParam(defaultValue = "1") Integer pageNum,
                          @RequestParam(defaultValue = "10") Integer pageSize){
        return cartService.getCart(pageNum, pageSize);
    }

    /**
     * 购物车单独商品数量加减
     * @param itemId
     * @param num
     * @return
     */
    @PatchMapping("numAdd")
    public Result numAdd(@RequestParam("itemId") Long itemId,
                         @RequestParam("num") Integer num){
        return cartService.numAdd(itemId, num);
    }

    /**
     * 修改购物车
     * @param cartDTO
     */
    @PutMapping
    public void updateCart(@RequestBody CartDTO cartDTO){
        Cart cart = BeanUtil.copyProperties(cartDTO, Cart.class);
        cart.setUserId(ThreadLocalUtil.get());
        cartService.updateById(cart);
    }

    /**
     * 删除单个购物商品
     * @param id
     * @return
     */
    @DeleteMapping("delete/{id}")
    public Result deleteCart(@PathVariable("id") Long id){
        // 参数校验
        if (id == null ) {
            throw new CommonException("参数不能为空");
        }
        return cartService.deleteCart(id);
    }

    /**
     * 批量删除购物车商品
     * @param ids
     * @return
     */
    @DeleteMapping
    public void deleteCartByIds(@RequestParam("ids")List<Long> ids){
        if(ids != null || ids.isEmpty()){
            throw new CommonException("谁让你传空集合");
        }
        try {
            LambdaQueryWrapper<Cart> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Cart::getUserId, ThreadLocalUtil.get())
                    .in(Cart::getItemId, ids);
            cartService.remove(queryWrapper);
            Result.success();
        } catch (Exception e) {
            throw new CommonException("批量删除购物车商品失败",e);
        }
    }
}
